package webserver.com.jaysun;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * @author jaysun
 * @descript :通过多线程模拟请求处理，返回资源
 */
public class Processor extends Thread {

	private static final String WEB_ROOT = "C:\\webserver\\requestdoc";
	private Socket socket;
	private InputStream in;
	// private OutputStream out;
	private PrintStream out;

	// 得到客户端请求,转换为输入流，构造输出流
	public Processor(Socket socket) {
		this.socket = socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 线程处理
	public void run() {
		// 模擬 解析請求場景
		String filename = parse(in);
		// filename.getBytes();
		// 将请求的内容发给客户端 
		sentFile(filename);
	}

	public String parse(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String filename = null;
		try {
			String httpMessage = br.readLine();
			String[] content = httpMessage.split(" ");
			if (content.length != 3) {
				sendErrorMessage(400, "Client query error");
			}

			System.out.println("code:" + content[0] + ",   filename" + content[1] + ",  http version=" + "" + content[2]);
			filename = content[1];//获得请求的文件名
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}

	//模拟错误页面
	public void sendErrorMessage(int errCode, String errorMessage) {
		out.println("HTTP/1.0" + errCode + " " + errorMessage);
		out.println("content-type: text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Message");
		out.println("</titel");
		out.println("<body>");
		out.println("<h1>ErrorCode:" + errCode + ",Message:" + errorMessage + "</h1>");
		out.println("</body");
		out.println("</html>");
	}
    
	//根据请求的文件名，找到文件，置入输出流
	public void sentFile(String filename) {
		File file = new File(Processor.WEB_ROOT + filename);
		if (!file.exists()) {
			sendErrorMessage(404, "File Not Found");
			return;
		}
		try {
			InputStream in = new FileInputStream(file);
			byte content[] = new byte[(int) file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 queryfile");
			out.println("content-length" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
